package org.oschina.api.discuss.order.dao;

import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.discuss.order.model.DiscussOrder;
import org.oschina.api.discuss.order.vo.DiscussOrderVo;
import org.springframework.stereotype.Repository;

@Repository
public class DiscussOrderDAO extends BaseDAO {

	private final String findVo[]={"id","name","color","`index`","font","_default","create_time"};

	/**
	 * 根据ID返回
	 * @param id
	 * @return
	 */
	public DiscussOrderVo findVoById(int id)
	{
		DiscussOrderVo cache=(DiscussOrderVo) getCacheHelper().hget(getIdKey(id), DiscussOrderVo.class);
		if(cache!=null)
			return cache;

		return _findById(id);
	}
	private DiscussOrderVo _findById(int id)
	{
		return (DiscussOrderVo) getQueryHelper().queryForObject_cache(findVo,new String[]{"id=?"}, new Object[]{id}, DiscussOrderVo.class);
	}

	/**
	 * 返回
	 * @return
	 */
	public List<DiscussOrderVo> findVo()
	{
		return getQueryHelper().query_cache(findVo, null, null, null, DiscussOrderVo.class, -1, -1);
	}

	/**
	 * 返回默认
	 * @return
	 */
	public DiscussOrderVo getDefault()
	{
		return (DiscussOrderVo) getQueryHelper().queryForObject_cache(findVo,new String[]{"_default=?"}, new Object[]{true}, DiscussOrderVo.class);
	}

	/**
	 * 更新
	 * @param discussOrder
	 * @return
	 */
	public int update(DiscussOrder discussOrder)
	{
		return (int) getQueryHelper().update_cache(new String[]{"name=?","color=?","font=?","`index`=?"}, new String[]{"id=?"},
				new Object[]{discussOrder.getName(),discussOrder.getColor(), discussOrder.getFont(), discussOrder.getIndex(), discussOrder.getId()}, DiscussOrderVo.class);
	}

	/**
	 * 取消所有默认
	 * 
	 * @return
	 */
	public int clearDefault()
	{
		return (int) getQueryHelper().update_cache(new String[]{"_default=?"}, null, new Object[] { false }, DiscussOrderVo.class);
	}

	/**
	 * 设置默认
	 * 
	 * @param id
	 * @return
	 */
	public int setDefault(int id)
	{
		return (int) getQueryHelper().update_cache(new String[]{"_default=?"}, new String[]{"id=?"}, new Object[]{true, id}, DiscussOrderVo.class);
	}

	/**
	 * 创建
	 * 
	 * @param discussOrder
	 * @return
	 */
	public DiscussOrder create(DiscussOrder discussOrder)
	{
		getQueryHelper().insert_cache(new String[]{"id", "name", "color", "font", "`index`","_default", "create_time" },
				new Object[]{ discussOrder.getId(), discussOrder.getName(), discussOrder.getColor(), discussOrder.getFont(), discussOrder.getIndex(), discussOrder.get_default(), discussOrder.getCreate_time() }, DiscussOrderVo.class);
		return discussOrder;
	}
	
	private String getIdKey(Object id)
	{
		return getKey(Constants.CACHE_DISCUSS_ORDER,id);
	}
}